import { autoUpdater } from "electron-updater";
import { app, BrowserWindow, ipcMain, Tray, Menu, screen } from "electron";
import { fileURLToPath } from "node:url";
import path from "node:path";
import checkUpdate from "./checkUpdate.js";
import logger from "./log";

// 运行vite时, vite会自动写入服务器的url
export const VITE_DEV_SERVER_URL = process.env["VITE_DEV_SERVER_URL"];

// 将文件路径转换为不同操作系统的路径格式
const __dirname = path.dirname(fileURLToPath(import.meta.url));

const iconPath = path.join(__dirname, "../dist", "icon.png");

// 主窗口
let mainWindow;
// 托盘
let tray;
// 提醒窗口
let remindWindow;

app.on("ready", async () => {
  //每次启动程序，就检查更新

  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  logger.info(`窗口设置 ${width}, ${height}`);

  mainWindow = new BrowserWindow({
    // 显示系统菜单
    frame: true,
    // titleBarStyle: "hidden",
    // 是否可以调整窗口大小
    resizable: false,
    width,
    height,
    icon: iconPath,
    webPreferences: {
      backgroundThrottling: false,
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, "../dist-electron", "preload.mjs"),
    },
  });

  if (VITE_DEV_SERVER_URL) {
    // 本地开发环境
    mainWindow.loadURL(VITE_DEV_SERVER_URL + "/main.html");
  } else {
    // 生产环境
    const url = path.join(__dirname, "../");
    mainWindow.loadURL(`file://${url}/dist/main.html`);
  }

  console.log("VITE_DEV_SERVER_URL", VITE_DEV_SERVER_URL);
  mainWindow.webContents.on("did-finish-load", () => {
    mainWindow.webContents.openDevTools({ mode: "bottom" });
  });

  // 移除默认工具栏以及禁用调试功能
  mainWindow.removeMenu();
  // 设置应用托盘
  setTray();

  // 主页面一旦加载完成后就开始执行检查更新
  // mainWindow.webContents.send("debug", "更新检测中...");
  checkUpdate(mainWindow);
});

app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

ipcMain.on("mainWindow:close", () => {
  mainWindow.hide();
});

ipcMain.on("remindWindow:close", () => {
  remindWindow.close();
});

ipcMain.on("setTaskTimer", (event, time, task) => {
  const now = new Date();
  const date = new Date();
  date.setHours(time.slice(0, 2), time.slice(3), 0);
  const timeout = date.getTime() - now.getTime();
  setTimeout(() => {
    createRemindWindow(task);
  }, timeout);
});

function setTray() {
  // 设置托盘图标
  logger.info(`iconPath=${iconPath}`);
  tray = new Tray(iconPath);
  logger.info(`任务列表`);
  tray.setToolTip("任务列表");
  tray.on("click", () => {
    if (mainWindow.isVisible()) {
      mainWindow.hide();
    } else {
      mainWindow.show();
    }
  });

  tray.on("right-click", () => {
    const menuConfig = Menu.buildFromTemplate([
      {
        label: "退出",
        click: () => app.quit(),
      },
    ]);

    tray.popUpContextMenu(menuConfig);
  });
}

function createRemindWindow(task) {
  if (remindWindow) remindWindow.close();
  remindWindow = new BrowserWindow({
    height: 450,
    width: 360,
    resizable: false,
    frame: true,
    icon: iconPath,
    show: false,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, "../dist-electron", "preload.mjs"),
    },
  });
  remindWindow.removeMenu();

  //获取屏幕尺寸
  const size = screen.getPrimaryDisplay().workAreaSize;
  //获取托盘位置的y坐标（windows在右下角，Mac在右上角）
  const { y } = tray.getBounds();
  //获取窗口的宽高
  const { height, width } = remindWindow.getBounds();
  //计算窗口的y坐标
  const yPosition = process.platform === "darwin" ? y : y - height;
  remindWindow.setBounds({
    x: size.width - width,
    y: yPosition,
    height,
    width,
  });

  remindWindow.setAlwaysOnTop(true);

  if (VITE_DEV_SERVER_URL) {
    remindWindow.loadURL(VITE_DEV_SERVER_URL + "/remind.html");
  } else {
    remindWindow.loadURL(`file://${__dirname}/dist/remind.html`);
  }

  remindWindow.webContents.on("did-finish-load", () => {
    remindWindow.webContents.send("setTask", task);
  });

  remindWindow.show();
  remindWindow.on("closed", () => {
    remindWindow = null;
  });
  setTimeout(() => {
    remindWindow && remindWindow.close();
  }, 50 * 1000);
}
